import router from "@/router"
import { useUserStore } from "@/stores/userStote"
import axios, { type Method } from "axios"
import { ElMessage } from "element-plus"

const service = axios.create({
  baseURL: 'http://geek.itheima.net/',
  timeout: 20 * 1000,
})

// 定义返回的数据类型
export interface ServiceResponse<T> {
  msg: string
  data: T
}

// 封装通用的请求方法
export const request = <T>(url: string, method: Method = 'GET', submitData?: object, params?: object) =>{
  if(params){
    return service.request<T,ServiceResponse<T>>({
      url,
      method,
      [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
      params
    })
  }else{
    return service.request<T,ServiceResponse<T>>({
      url,
      method,
      [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
    })
  }
}


// 请求拦截器
service.interceptors.request.use(
  config => {
    // 携带token操作
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
   
    return config
  },
  error => {
    return Promise.reject(error)
  },
)
// 响应拦截器
service.interceptors.response.use(
  response => {

    return response.data
  },
  error => {
    // 拦截错误并处理
    if(error.response){
      ElMessage.error(error.response.data.message)
      if(error.response.status === 401){
        // 清除token和用户信息
        const userStore = useUserStore()
        userStore.removeToken()
        router.push('/login')
      }
    }else{
      ElMessage.error('网络出现错误，请稍后再试')
    }
    return Promise.reject(error)
  },
)

export default service